// dicmgr.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "dicmgr.h"
#include "..\\Common\\com.h"

/////////////////////////////////////////////////////////////////
// Globals
//
/////////////////////////////////////////////////////////////////
DWORD g_dwFlags = CommandInstructions::CreateDatabase | CommandInstructions::SpecifyPassword;

CString g_DatabaseName, g_Password;

int _tmain(int argc, _TCHAR* argv[])
{
	// Parse command line arguments, if any; this will update
   // the value of g_dwFlags as appropriate for the arguments.
   if ( !ParseCommandLine() )
   {
	  DisplayInstructions();
      return EXIT_FAILURE;
   }

   HRESULT      hr;
   // Initialize OLE
   hr = CoInitialize(NULL);
   if ( FAILED(hr) )
      return EXIT_FAILURE;

   IDicMgmt* pDigMgmt=NULL;

   CHECK_HR(hr=CoCreateInstance(CLSID_DicMgmt,NULL, CLSCTX_INPROC_SERVER, IID_IDicMgmt, (LPVOID*) &pDigMgmt));

   if(g_dwFlags & CommandInstructions::CreateDatabase)
   {
	   if(g_dwFlags & CommandInstructions::SpecifyPassword)
	   {
		   CHECK_HR(hr=CreateDb(pDigMgmt, g_DatabaseName, g_Password));
	   }
	   else
	   { // you didn't specify the table name
		   _ftprintf(stderr, _TEXT("Please specify a table name\n"));
		   DisplayInstructions();
	   }
   }

CLEANUP:

   if(pDigMgmt)
	   pDigMgmt->Release();

   CoUninitialize();

   if( FAILED(hr) )
      return EXIT_FAILURE;

	return EXIT_SUCCESS;
}
void DisplayInstructions()
{
	_ftprintf(stderr, _TEXT("Usage: %s [-c] database [-p] password [-h] \n\nWhere:\n") \
		_TEXT("c = Create database\n") \
		_TEXT("p = Specify database password.\n") \
		_TEXT("h = Display this help\n"),
	#if !defined(UNICODE)
			__argv[0]
	#else
			__wargv[0]
	#endif
        );
}

BOOL ParseCommandLine () 
{
   int      iArg;
   TCHAR *   psz;

   // Set the locale for all C run-time functions.
   //setlocale(LC_ALL, ".ACP");

   // Go through each command line argument and set the appropriate
   // bits in g_dwFlags, depending on the chosen options.
   if(__argc<2)
	   return FALSE;
   for ( iArg = 1; iArg < __argc; iArg++ ) 
   {
      // Inspect the current argument string.
#if !defined(UNICODE)
      psz = __argv[iArg];
#else
	   psz = __wargv[iArg];
#endif

      // Valid options begin with '-' or '/'.
      if( psz[0] == _TEXT('-') || psz[0] ==_TEXT( '/') ) {
         // The next character is the option.
         switch( _totlower(psz[1]) ) {
         case _TEXT('p'):
            g_dwFlags |= CommandInstructions::SpecifyPassword;
			g_Password=__wargv[iArg+1];
			if(g_Password.IsEmpty())
				return FALSE;
			iArg++; // skip the following table name parameter
            continue;
         case _TEXT('c'):
            g_dwFlags |= CommandInstructions::CreateDatabase;
			g_DatabaseName=__wargv[iArg+1];
			if(g_DatabaseName.IsEmpty())
				return FALSE;
			iArg++; // skip the following database name parameter;
            continue;
         case _TEXT('h'):
			DisplayInstructions();
            continue;
         }
      }

	  // invalid argument
	  return FALSE;
   }

   return TRUE;
}

HRESULT CreateDb( IDicMgmt* pDicMgr, CString& strDB, CString& strPwd)
{
	HRESULT hr=S_OK;

	CComBSTR bstrDB(strDB), bstrPwd(strPwd);
	CHECK_HR(hr=pDicMgr->CreateDicFile(bstrDB, bstrPwd));

CLEANUP:
	 if(FAILED(hr))
	   HandleError();
	return hr;
}

HRESULT HandleError()
{
	HRESULT hr=S_OK;
	IErrorInfo * pErrorInfo=NULL;

	hr=GetErrorInfo(0, &pErrorInfo);
	if(hr==S_FALSE)
	{
		_ftprintf(stderr,_TEXT("failed to retrieve detail error.\n"));
		return hr;
	}

	CString message;
	CComBSTR bstrSource, bstrDescription;

	hr=pErrorInfo->GetSource(&bstrSource);
	if(FAILED(hr))
	{
		_ftprintf(stderr,_TEXT("failed to retrieve IErrorInfo source.\n"));
		goto CLEANUP;
	}

	hr=pErrorInfo->GetDescription(&bstrDescription);
	if(FAILED(hr))
	{
		_ftprintf(stderr,_TEXT("failed to retrieve IErrorInfo description.\n"));
		goto CLEANUP;
	}

	// here: if you compile as MBCS, ti will report error
	message.Format(_TEXT("[%s]:%s\n"),bstrSource, bstrDescription);

	_ftprintf(stderr,_TEXT("%s.\n"), message);

CLEANUP:
	if(pErrorInfo)
		pErrorInfo->Release();
	return hr;
}